#include "server.h"
#include "myconfig.h"
#include "ui_server.h"

Server::Server(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Server)
{
    ui->setupUi(this);
    mydb=new MyDB();
    if(!mydb->Mydb_ok())
    {
        ui->State->setText("database connect failed!");
        QMessageBox::warning(this,"error","connect failed!");
        close();
    }
    else
    {
        //QSqlQuery query;
        //QString q="select password from test where username='test';";
        //query.exec(q);
        //while(query.next())
        //    qDebug()<<query.value(0);
        ui->State->setText("database connect successful!");
    }
    tcpServer = new QTcpServer(this);
    if(!tcpServer->listen(QHostAddress::Any,6666))
    {
        ui->State->setText(tcpServer->errorString());
        QMessageBox::warning(this,"error","connect failed!");
        close();
    }
    connect(tcpServer,SIGNAL(newConnection()),this,SLOT(getMessage()));
}

Server::~Server()
{

    tcpServer->close();
    delete mydb;
    delete ui;
}


void Server::getMessage()
{
    m_client=tcpServer->nextPendingConnection();
    qDebug()<<"new connect";
    qDebug()<<m_client->peerAddress().toString();
    //QByteArray block;
    // 使用数据流写入数据
    //QDataStream out(&block,QIODevice::WriteOnly);
    //out<<"1123";
    //m_client->write(block);
    connect(m_client,SIGNAL(readyRead()),this,SLOT(getData()));

    //m_client->close();
}

void Server::getData()
{
    QByteArray datagram=m_client->readAll();
    //qDebug()<<datagram.size();
    QString string(datagram);
    qDebug()<<string;
    ui->State->setText(string);
    QByteArray block;
    //QDataStream out(&block,QIODevice::WriteOnly);
    QString rtv=mydb->SqlExec(string);
    block=rtv.toLatin1();
    char* ch=block.data();
    ui->State->setText(rtv);
    m_client->write(ch);
    m_client->close();
}
